#include <stdlib.h>
#include <stdio.h>
#include "list.h"

node * list_find(list * l, void * elt){
  node * tmp = l->first;
  while(tmp != NULL && tmp->data != elt){
    tmp=tmp->next;
  }
  return tmp;
}

int list_isempty(list * l){
  return (l->first==NULL);
}

list * list_new(void){
  list * ret = (list *)malloc(sizeof(struct _list));
  ret->first = NULL;
  ret->last = NULL;
  return ret;
}

list * list_add (list * l, void * elt){
  node * new_elt = (node *) malloc(sizeof(struct _node));
  new_elt->data = elt;
  new_elt->next=NULL;
  if(l->first==NULL){ // liste vide
    l->first = new_elt;
    l->last = new_elt;
  }
  else{
    l->last->next = new_elt;
    l->last = new_elt;
  }
  return l;
}

list * list_remove (list * l, void * elt){
  node * tmp = l->first;
  if(tmp->data == elt){ // l'élément à supprimer est le premier de la liste
    l->first = tmp->next;
    if(tmp->next == NULL){ // la liste ne comporte qu'un élément
      l->last = NULL;
    }
    free(tmp);
    return l;
  }
  else{
    node * tmp2 = tmp;
    while(tmp != NULL && tmp->data != elt){
      tmp2 = tmp;
      tmp = tmp->next;
    }
    if(tmp == NULL){ // élément pas trouvé
      return l;
    }
    else{
      tmp2->next = tmp->next;
      if(l->last == tmp){ // si l'élément à supprimer est le dernier de la liste
	l->last = tmp2;
      }
      free(tmp);
      return l;
    }
  }
}

void list_free(list * l){
  node * tmp = l->first;
  node * tmp2;
  while(tmp!=NULL){
    tmp2 = tmp;
    tmp = tmp->next;
    free(tmp2);
  }
  free(l);
}

void list_print(list * l){
  node * tmp = l->first;
  unsigned int i=0;
  printf("\nlist %p :\n\n",l);
  while(tmp != NULL){
    printf("Element %d (address %p) : %p\n",i++,tmp,tmp->data);
    tmp = tmp->next;
  }
  printf("\n");
}
